package com.test.web.service;

import cn.hutool.json.JSONUtil;
import com.he.core.ResultT;
import com.he.core.security.MD5;
import com.he.web.util.Jwt;
import com.test.web.bean.vue.req.LoginReq;
import com.test.web.bean.vue.res.LoginRes;
import com.test.web.bean.vue.res.user.InfoRes;
import com.test.web.dao.BackuserDao;
import com.test.web.entity.Backuser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author heyanjing
 * date:2020-07-03 2020/7/3:9:58
 */
@Service
public class BackuserService {

    @Resource
    private BackuserDao backuserDao;

    /**
     * 登录
     * 只返回 token及token的刷新时间
     */
    public ResultT<LoginRes> login(LoginReq bean) {
        String account = bean.getUsername();
        String password = bean.getPassword();
        Backuser backuser = backuserDao.getByAccount(account);
        if (backuser == null) {
            return ResultT.errorWithCodeAndMsg(1001, "账户不存在");
        }
        String salt = backuser.getSalt();
        String pwd = backuser.getPwd();
        if (!pwd.equals(MD5.md5Hex(password + salt))) {
            return ResultT.errorWithCodeAndMsg(1002, "密码错误");
        }
        LoginRes loginRes = getLoginRes(backuser);
        return ResultT.successWithData(loginRes);

    }

    private LoginRes getLoginRes(Backuser backuser) {
        int expiration = 3600000;
        String token = Jwt.createJWT(JSONUtil.toJsonStr(backuser), backuser.getBackUserId(), expiration);
        return new LoginRes().setToken(token).setExpiration(expiration);
    }

    /**
     * 获取用户信息
     * 返回用户的 昵称、头像、角色、权限、是否超管
     */
    public ResultT<InfoRes> info(Backuser backuser) {
        //数据库查询真实的数据
        InfoRes infoRes = new InfoRes().setName("超管").setAvatar("http://cnd.manguocloud.com/1593614934041.jpg").setRoles("超级管理员").setPerms("A,A1,A2,B,B1,B2").setSupper(true);
        return ResultT.successWithData(infoRes);
    }

    /**
     * 刷新token
     */
    public ResultT<LoginRes> refresh(Backuser backuser) {
        LoginRes loginRes = getLoginRes(backuser);
        return ResultT.successWithData(loginRes);
    }

}
